package luob.common;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import luob.iservice.module.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by luob on 15/6/13.
 */
public class Util {
    //20150612 by luob
    //use session and cookie at the same time , ensure random client_id
    public static String getClientId(Controller ctx) {
        String result = "";
        result = ctx.getSessionAttr("iservice_client_id");
        result = result == null ? "" : result;
        if (!StrKit.isBlank(result)) {
            ctx.setCookie("cookie_user", JsonKit.toJson(User.me.findById(result, "uid,username")), 3600 * 24 * 7);
        }
        return result;
    }

    public static void login(Controller ctx, String userId) {
        ctx.setSessionAttr("iservice_client_id", userId);
        ctx.setCookie("cookie_user", JsonKit.toJson(User.me.findById(userId, "uid,username")), 3600 * 24 * 7);
    }

    public static void logout(Controller ctx) {
        ctx.setSessionAttr("iservice_client_id", "");
    }

    //deepCopyList tool from web
    public static List<?> deepCopyList(List<?> src) throws Exception {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
        objOut.writeObject(src);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(
                byteOut.toByteArray());
        ObjectInputStream objIn = new ObjectInputStream(byteIn);
        return (List<?>) objIn.readObject();
    }

    public static int getPageIndex(Controller ctx) {
        return ctx.getParaToInt("page", 1);
    }

    public static int getPageSize(Controller ctx) {
        return ctx.getParaToInt("pageSize", 10);
    }

    public static String getDefaultDateStr(Date d) {
        //return DateKit.toStr(d, DateKit.timeFormat);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
    }

    public static Date getDefaultDateFromStr(String dstr) {
        //return DateKit.toDate(dstr);
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dstr);
        } catch (ParseException e) {
            return null;
        }
    }
}
